package com.notificationtester;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SetScheduledNotification extends Activity {
	
	private PendingIntent mAlarmSender;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mAlarmSender = PendingIntent.getService(SetScheduledNotification.this,
                0, new Intent(SetScheduledNotification.this, NotificationService.class), 0);
        
        setContentView(R.layout.main);
        
        Button button = (Button)findViewById(R.id.start_notifications);
        button.setOnClickListener(mStartListener);
        button = (Button)findViewById(R.id.stop_notifications);
        button.setOnClickListener(mStopListener);
    }
    
    private OnClickListener mStartListener = new OnClickListener() { 
    	 public void onClick(View v) {
    		 
    		 Intent i = new Intent(getApplicationContext(), SetScheduledNotification.class);
    		 PendingIntent pendingIntent =
    		 PendingIntent.getService(getApplicationContext(), 0, i, 0);

    		 AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    		 
    		 Calendar calendar = Calendar.getInstance();

    		 Calendar calendarTimetoStart = (Calendar)calendar.clone();

    		 // start service at specific time.
    		 // start service at specific date.

    		 calendarTimetoStart.set(Calendar.HOUR_OF_DAY, 3);
    		 calendarTimetoStart.set(Calendar.MINUTE, 59);
    		 calendarTimetoStart.set(Calendar.SECOND, 0);

    		 long diffInTime = calendarTimetoStart.getTimeInMillis() - calendar.getTimeInMillis();

    		 long firstWake = System.currentTimeMillis() + diffInTime;

    		 am.set(AlarmManager.RTC, firstWake, pendingIntent);


             Toast.makeText(SetScheduledNotification.this, R.string.repeating_scheduled,
                     Toast.LENGTH_LONG).show();
         }
    };
    
    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            // And cancel the alarm.
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(mAlarmSender);

            // Tell the user about what we did.
            Toast.makeText(SetScheduledNotification.this, R.string.repeating_unscheduled,
                    Toast.LENGTH_LONG).show();

        }
    };
}